### Bootstrap the post-WW2 model specification

date()
library("tidyverse")
library("foreach")
library("maxLik")
source("backend_main.r")
sessionInfo()


load("confirm_boot_postwar.rda")
load("results/fit_postwar.rda")
load("results/boot_index_postwar.rda")


## Set to FALSE to estimate from scratch (takes much longer)
CONFIRM_MODE <- TRUE

## Run bootstrap using indices generated in previous script
boot_postwar <- vector("list", length(fit_postwar))
for (i in seq_along(boot_postwar)) {
  fit <- fit_postwar[[i]]
  boot_postwar[[i]] <- foreach (b = 1:100, .combine = "rbind") %do% {
    cat("Imputation ", i, ", bootstrap iteration ", b, ", ", date(), "\n", sep = "")
    id_disp_boot <- boot_index_postwar[[i]][b, ]
    id_map <- tibble(id = seq_along(id_disp_boot), id_old = id_disp_boot)
    boot_dispute <-  left_join(id_map,
                               fit$data_dispute,
                               by = c("id_old" = "id"))
    boot_participant <- left_join(id_map,
                                  fit$data_participant,
                                  by = c("id_old" = "id"))
    if (CONFIRM_MODE) {
      init <- confirm_boot_postwar[[i]][b, ]
    } else {
      init <- NULL
    }
    boot_cf <- est_structwar_ac(f_dispute = fit$f_dispute,
                                f_participant = fit$f_participant,
                                data_dispute = boot_dispute,
                                data_participant = boot_participant,
                                n_halton = fit$n_halton,
                                coef_only = TRUE,
                                init = init,
                                scale = FALSE,
                                reltol = 1e-14,
                                iterlim = 5000,
                                useGrad = TRUE,
                                finalHessian = FALSE,
                                printLevel = 1)
    boot_cf
  }
}


save(boot_postwar, file = "results/boot_postwar.rda")


date()
